#ifndef __M_HTTP_H__
#define __M_HTTP_H__

#include <iostream>
#include <fstream>
#include <string>
#include <list>
#include <unordered_map>
#include <functional>
#include <vector>
#include <regex>
#include <sys/stat.h>
#include "../reactor.hpp"

#define MAX_LINE_SIZE 8192
typedef enum {
    /*当前处于获取请求行状态*/
    RECV_REQ_LINE,
    /*当前处于获取头部状态*/
    RECV_REQ_HEAD,
    /*当前处于获取正文状态*/
    RECV_REQ_BODY,
    /*当前处于完成请求所有数据获取完毕状态*/
    RECV_REQ_OVER,
    /*接收请求数据出错*/
    RECV_REQ_ERROR,
}HttpState;


class Util {
    public:
        static int split(const std::string &body, const std::string &seg, std::vector<std::string> *arry) {
            size_t pos, idx = 0, count = 0;
            arry->clear();
            while(idx < body.size()) {
                pos = body.find(seg, idx);
                if (pos == std::string::npos) {
                    break;
                }   
                std::string val = body.substr(idx, pos - idx);
                if (val.size() == 0) {
                    idx = pos + seg.size();
                    continue;
                }
                arry->push_back(val);
                idx = pos + seg.size();
                count++;
            }   
            if (idx < body.size()) {
                arry->push_back(body.substr(idx));
                count++;
            }   
            return count;
        }
        static bool read_file(const std::string &path, std::string *body) {
            if (is_file(path) == false) {
                ERR_LOG("%s file is not exists!", path.c_str());
                return false;
            }
            std::ifstream ifs(path.c_str(), std::ios::in|std::ios::binary);
            if (ifs.is_open() == false) {
                ERR_LOG("%s open file failed!", path.c_str());
                return false;
            }   
            size_t fsize = 0;
            ifs.seekg(0, std::ios::end);
            fsize = ifs.tellg();
            ifs.seekg(0, std::ios::beg);
            body->resize(fsize);
            ifs.read(&(*body)[0], fsize);
            if (ifs.good() == false) {
                ERR_LOG("read file content failed!");
                ifs.close();
                return false;
            }   
            ifs.close();
            return true;
        }
        static bool write_file(const std::string &path, const std::string &body) {
            std::ofstream ofs(path.c_str(), std::ios::out|std::ios::trunc|std::ios::binary);
            if (ofs.is_open() == false) {
                ERR_LOG("%s open file failed!", path.c_str());
                return false;
            }
            ofs.write(&body[0], body.size());
            if (ofs.good() == false) {
                ERR_LOG("write file content failed!");
                ofs.close();
                return false;
            }   
            ofs.close();
            return true;
        }
        static int hex_to_i(char ch) {
            if (ch >= '0' && ch <= '9') {
                return (ch - '0');
            }else if (ch >= 'a' && ch <= 'z') {
                return (ch - 'a' + 10);
            }else if (ch >= 'A' && ch <= 'Z') {
                return (ch - 'A' + 10);
            }   
            return -1; 
        }
        static std::string urldecode(const std::string &url, bool convert_plus_to_space){
            std::string res;
            for (int i = 0; i < url.size(); i++) {
                if (url[i] == '%' && (i+1) < url.size()) {
                    int v1 = hex_to_i(url[i+1]);
                    int v2 = hex_to_i(url[i+2]);
                    if (v1 >= 0 && v2 >= 0) {
                        res += v1 * 16 + v2; 
                        i += 2;
                    }else {
                        res += v1*16;
                        i+=1;
                    }   
                }else if (convert_plus_to_space && url[i] == '+') {
                    res += ' ';
                }else {
                    res += url[i];
                }   
            }   
            return res;
        }
        static std::string urlencode(const std::string &url){
            return "";
        }
        static std::string find_file_mime_type(const std::string &path) {
            static const std::unordered_map<std::string, std::string> ext_mime_map = {
                {".aac",        "audio/aac"},
                {".abw",        "application/x-abiword"},
                {".arc",        "application/x-freearc"},
                {".avi",        "video/x-msvideo"},
                {".azw",        "application/vnd.amazon.ebook"},
                {".bin",        "application/octet-stream"},
                {".bmp",        "image/bmp"},
                {".bz",         "application/x-bzip"},
                {".bz2",        "application/x-bzip2"},
                {".csh",        "application/x-csh"},
                {".css",        "text/css"},
                {".csv",        "text/csv"},
                {".doc",        "application/msword"},
                {".docx",       "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
                {".eot",        "application/vnd.ms-fontobject"},
                {".epub",       "application/epub+zip"},
                {".gif",        "image/gif"},
                {".htm",        "text/html"},
                {".html",       "text/html"},
                {".ico",        "image/vnd.microsoft.icon"},
                {".ics",        "text/calendar"},
                {".jar",        "application/java-archive"},
                {".jpeg",       "image/jpeg"},
                {".jpg",        "image/jpeg"},
                {".js",         "text/javascript"},
                {".json",       "application/json"},
                {".jsonld",     "application/ld+json"},
                {".mid",        "audio/midi"},
                {".midi",       "audio/x-midi"},
                {".mjs",        "text/javascript"},
                {".mp3",        "audio/mpeg"},
                {".mpeg",       "video/mpeg"},
                {".mpkg",       "application/vnd.apple.installer+xml"},
                {".odp",        "application/vnd.oasis.opendocument.presentation"},
                {".ods",        "application/vnd.oasis.opendocument.spreadsheet"},
                {".odt",        "application/vnd.oasis.opendocument.text"},
                {".oga",        "audio/ogg"},
                {".ogv",        "video/ogg"},
                {".ogx",        "application/ogg"},
                {".otf",        "font/otf"},
                {".png",        "image/png"},
                {".pdf",        "application/pdf"},
                {".ppt",        "application/vnd.ms-powerpoint"},
                {".pptx",       "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
                {".rar",        "application/x-rar-compressed"},
                {".rtf",        "application/rtf"},
                {".sh",         "application/x-sh"},
                {".svg",        "image/svg+xml"},
                {".swf",        "application/x-shockwave-flash"},
                {".tar",        "application/x-tar"},
                {".tif",        "image/tiff"},
                {".tiff",       "image/tiff"},
                {".ttf",        "font/ttf"},
                {".txt",        "text/plain"},
                {".vsd",        "application/vnd.visio"},
                {".wav",        "audio/wav"},
                {".weba",       "audio/webm"},
                {".webm",       "video/webm"},
                {".webp",       "image/webp"},
                {".woff",       "font/woff"},
                {".woff2",      "font/woff2"},
                {".xhtml",      "application/xhtml+xml"},
                {".xls",        "application/vnd.ms-excel"},
                {".xlsx",       "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
                {".xml",        "application/xml"},
                {".xul",        "application/vnd.mozilla.xul+xml"},
                {".zip",        "application/zip"},
                {".3gp",        "video/3gpp"},
                {".3g2",        "video/3gpp2"},
                {".7z",         "application/x-7z-compressed"},
            };
            size_t pos = path.find_last_of(".");
            if (pos == std::string::npos) {
                return "application/octet-stream";
            }
            std::string ext = path.substr(pos);
            //std::cout << "ext:" << ext << std::endl;
            auto it = ext_mime_map.find(ext);
            if (it != ext_mime_map.end()) {
                return it->second;
            }
            return "application/octet-stream";
        }
        static std::string status_message(int status) {
            switch (status) {
                case 100: return "Continue";
                case 101: return "Switching Protocol";
                case 102: return "Processing";
                case 103: return "Early Hints";
                case 200: return "OK";
                case 201: return "Created";
                case 202: return "Accepted";
                case 203: return "Non-Authoritative Information";
                case 204: return "No Content";
                case 205: return "Reset Content";
                case 206: return "Partial Content";
                case 207: return "Multi-Status";
                case 208: return "Already Reported";
                case 226: return "IM Used";
                case 300: return "Multiple Choice";
                case 301: return "Moved Permanently";
                case 302: return "Found";
                case 303: return "See Other";
                case 304: return "Not Modified";
                case 305: return "Use Proxy";
                case 306: return "unused";
                case 307: return "Temporary Redirect";
                case 308: return "Permanent Redirect";
                case 400: return "Bad Request";
                case 401: return "Unauthorized";
                case 402: return "Payment Required";
                case 403: return "Forbidden";
                case 404: return "Not Found";
                case 405: return "Method Not Allowed";
                case 406: return "Not Acceptable";
                case 407: return "Proxy Authentication Required";
                case 408: return "Request Timeout";
                case 409: return "Conflict";
                case 410: return "Gone";
                case 411: return "Length Required";
                case 412: return "Precondition Failed";
                case 413: return "Payload Too Large";
                case 414: return "URI Too Long";
                case 415: return "Unsupported Media Type";
                case 416: return "Range Not Satisfiable";
                case 417: return "Expectation Failed";
                case 418: return "I'm a teapot";
                case 421: return "Misdirected Request";
                case 422: return "Unprocessable Entity";
                case 423: return "Locked";
                case 424: return "Failed Dependency";
                case 425: return "Too Early";
                case 426: return "Upgrade Required";
                case 428: return "Precondition Required";
                case 429: return "Too Many Requests";
                case 431: return "Request Header Fields Too Large";
                case 451: return "Unavailable For Legal Reasons";
                case 501: return "Not Implemented";
                case 502: return "Bad Gateway";
                case 503: return "Service Unavailable";
                case 504: return "Gateway Timeout";
                case 505: return "HTTP Version Not Supported";
                case 506: return "Variant Also Negotiates";
                case 507: return "Insufficient Storage";
                case 508: return "Loop Detected";
                case 510: return "Not Extended";
                case 511: return "Network Authentication Required";

                default:
                case 500: return "Internal Server Error";
            }
            return "Internal Server Error";
        }
        static bool is_file(const std::string &path) {
            struct stat st;
            return stat(path.c_str(), &st) >= 0 && S_ISREG(st.st_mode);
        }
        static bool is_dir(const std::string &path) {
            struct stat st;
            return stat(path.c_str(), &st) >= 0 && S_ISDIR(st.st_mode);
        }
        static bool is_valid_path(const std::string &path) {
            int level = 0;
            std::vector<std::string> arry;
            split(path, "/", &arry);
            for (auto &it : arry) {
                if (it == "..") {
                    if (level == 0) {
                        return false;
                    }
                    level--;
                }else {
                    level++;
                }
            }
            return true;
        }
};

class HttpRequest {
    public:
        std::string version;
        std::string method;
        std::string path;
        std::string body;
        std::smatch matches;
        std::unordered_map<std::string, std::string> headers;
        std::unordered_map<std::string, std::string> params;
    public:
        void reset() {
            version.clear();
            method.clear();
            path.clear();
            body.clear();
            headers.clear();
            params.clear();
            std::smatch tmp;
            matches.swap(tmp);
        }
        bool has_header(const std::string &key) {
            auto it = headers.find(key);
            if (it == headers.end()) {
                return false;
            }
            return true;
        }
        std::string get_header(const std::string &key) {
            return headers[key];
        }
        size_t content_length() {
            if (has_header("Content-Length") == false) {
                return 0;
            }
            std::string len = get_header("Content-Length");
            return std::stol(len);
        }
        bool is_close() {
            if (!has_header("Connection") || (has_header("Connection") && get_header("Connection") == "close")) {
                return true;
            }
            return false;
        }
};
class HttpResponse {
    public:
        int statu;
        bool is_redirect;
        std::string version;
        std::string body;
        std::string redirect_url;
        std::unordered_map<std::string, std::string> headers;
    public:
        HttpResponse(int s):statu(s), is_redirect(false) {}
        HttpResponse():statu(200), is_redirect(false) {}
        bool has_header(const std::string &key) {
            auto it = headers.find(key);
            if (it == headers.end()) {
                return false;
            }
            return true;
        }
        std::string get_header(const std::string &key) {
            return headers[key];
        }
        void set_header(const std::string &key, const std::string &val) {
            headers[key] = val;
            return ;
        }
        void set_content(const std::string &data, const std::string &content_type = "text/plain") {
            body = std::move(data);
            set_header("Content-Type", content_type);
            return;
        }
        void set_redirect(int status = 302, const std::string &url = "/") {
            statu = status;
            redirect_url = url;
            return ;
        }
        bool is_close() {
            if (!has_header("Connection") || (has_header("Connection") && get_header("Connection") == "close")) {
                return true;
            }
            return false;
        }
};
/*Context类是一个协议上下文类，由HttpServer对象设置给TcpServer最终设置给通信socket的Connection对象*/
/*在Connction对象创建完毕后进行设置，主要是防止一次接收的数据中不是一个完整的请求，因此保存的上下文信息以及请求信息*/
class HttpContext {
    public:
        HttpContext():_recv_statu(RECV_REQ_LINE),_resp_statu(200) {}
        void reset() { 
            _recv_statu = RECV_REQ_LINE;
            _resp_statu = 200;
            _req.reset();
        }
        int resp_statu() { return _resp_statu; }
        HttpState recv_statu() { return _recv_statu; }
        HttpRequest & request() { return _req; }
        /*http请求接收解析，根据上下文不同状态进行请求不同部分的接收*/
        void recv_http_request(bit_net::Buffer *buffer) {
            if (_recv_statu == RECV_REQ_LINE) {
                std::string line;
                std::string req_line = buffer->getline();
                /*这表示当前接收缓冲区中不是一个完整的行*/
                if (req_line.empty()) {
                    if (buffer->readable_size() > MAX_LINE_SIZE) {
                        _resp_statu = 414;
                        _recv_statu = RECV_REQ_ERROR;
                    }
                    return ;
                }
                /*请求行过长*/
                if (req_line.size() > MAX_LINE_SIZE) {
                    _resp_statu = 414;
                    _recv_statu = RECV_REQ_ERROR;
                    return;
                }
                bool ret = parse_request_line(req_line);
                if (ret == false) {
                    _resp_statu = 400;
                    _recv_statu = RECV_REQ_ERROR;
                    return;
                }
                _recv_statu = RECV_REQ_HEAD;
            }
            if (_recv_statu == RECV_REQ_HEAD) {
                while(buffer->readable_size() > 0) {
                    std::string head_line = buffer->getline();
                    if (head_line.size() > MAX_LINE_SIZE) {
                        _resp_statu = 414;
                        _recv_statu = RECV_REQ_ERROR;
                        return;
                    }
                    /*这表示当前接收缓冲区中不是一个完整的行*/
                    if (head_line.empty()) {
                        /*但是缓冲区中有数据，且长度超过了最大行长度，则错误返回*/
                        if (buffer->readable_size() > MAX_LINE_SIZE) {
                            _resp_statu = 414;
                            _recv_statu = RECV_REQ_ERROR;
                        }
                        return;
                    }
                    if (head_line == "\r\n" || head_line == "\n") {
                        _recv_statu = RECV_REQ_BODY;
                        break;
                    }
                    bool ret = parse_header_line(head_line);
                    if (ret == false) {
                        _resp_statu = 400;
                        _recv_statu = RECV_REQ_ERROR;
                        return;
                    }
                }
            }
            if (_recv_statu == RECV_REQ_BODY) {
                int64_t body_len = _req.content_length();
                /*没有正文则请求接收完毕*/
                if (body_len == 0) {
                    _recv_statu = RECV_REQ_OVER;
                    return ;
                }
                INF_LOG("recv body: %d -- %d -- %d", body_len, _req.body.size(), buffer->readable_size());
                /*有正文则取出正文*/
                size_t rlen = body_len - _req.body.size();
                /*缓冲区中可读数据长度大于需要接收的正文长度，那就取剩下的部分就行，取完后请求接收完毕*/
                if (rlen <= buffer->readable_size()) {
                    _req.body.append(buffer->retrieve_as_string(rlen));
                    _recv_statu = RECV_REQ_OVER;
                    return ;
                }
                /*缓冲区可读数据长度不足需要接收的正文长度，则全取出，继续等下次数据到来*/
                _req.body.append(buffer->retrieve_all_as_string());
            }
        }
    private:
        bool parse_request_line(std::string &line) {
            /*(GET|HEAD|POST|PUT|DELETE) 匹配这几个字符串中的任意一个*/
            /*([^?]+) 负值匹配，匹配任意非?字符  +表示匹配一次或多次*/
            /*(?:\\?(.*?))   ?:为非获取匹配  \\? 表示?字符  .表示任意非\r\n字符， *匹配前边字符任意次*/
            std::regex re("(GET|HEAD|POST|PUT|DELETE) (([^?]+)(?:\\?(.*?))?) (HTTP/1\\.[01])(?:\r\n|\n)"); 
            std::smatch matches;
            bool ret = std::regex_match(line, matches, re);
            if (ret == false) {
                ERR_LOG("regex match request line failed!");
                return false;
            }
            /*matches[0]    整体首行    GET /zhangwenchao?a=b&c=d HTTP/1.1 */
            /*matches[1]    请求方法    GET */
            /*matches[2]    整体URL     /zhangwenchao?a=b&c=d   */
            /*matches[3]    ?之前       /zhangwenchao   */
            /*matches[4]    查询字符串  a=b&c=d */
            /*matches[5]    协议版本    HTTP/1.1    */
            _req.version = matches[5];
            _req.method = matches[1];
            _req.path = Util::urldecode(matches[3], false);
            if (matches[4].length() > 0) {
                std::vector<std::string> arry;
                Util::split(matches[4], "&", &arry);
                for (const auto &it : arry) {
                    size_t pos = it.find("=");
                    if (pos == std::string::npos) continue;
                    std::string key = Util::urldecode(it.substr(0, pos), true);
                    std::string val = Util::urldecode(it.substr(pos + 1), true);
                    _req.params[key] = val;
                }
            }
            return true;
        }
        bool parse_header_line(std::string &line) {
            size_t pos = line.find(": ");
            if (pos == std::string::npos) {
                return false;
            }
            std::string key = line.substr(0, pos);
            std::string val = line.substr(pos + 2);
            _req.headers[key] = val;
            return true;
        }
    private:
        int _resp_statu;
        HttpState _recv_statu;
        HttpRequest _req;
};
class HttpServer {
    public:
        using Handler = std::function<void(const HttpRequest &, HttpResponse *)>;
        using Handlers = std::vector<std::pair<std::regex, Handler>>;
        HttpServer(bit_net::EventLoop *loop, int port):_server(loop, port) {
            _server.set_connected_callback(std::bind(&HttpServer::connected_complate_callback, this, std::placeholders::_1));
            _server.set_message_callback(std::bind(&HttpServer::on_message_callback, this, std::placeholders::_1, std::placeholders::_2));
        }
        void connected_complate_callback(const bit_net::ConnectionPtr &conn) {
            DBG_LOG("new Connection:%p; socket:%d", conn.get(), conn->fd());
            /*设置一个请求接收上下文，等消息来了，根据上下文信息进行不同阶段的接收处理*/
            conn->set_context(HttpContext());
        }
        void on_message_callback(const bit_net::ConnectionPtr &conn, bit_net::Buffer *buffer) {
            HttpContext *context = conn->get_context()->get<HttpContext>();
            context->recv_http_request(buffer);
            /*因为有可能会出现当前接收的请求还不完整，因此错误和路由两个处理都要放到判断内*/
            if (context->recv_statu() == RECV_REQ_ERROR) {
                HttpResponse resp(context->resp_statu());
                error_handler(context->request(), &resp);
                write_response(conn, context->request(), resp);
                context->reset();
                conn->shutdown();
            }else if (context->recv_statu() == RECV_REQ_OVER) {
                HttpResponse resp;
                routing(context->request(), &resp);
                write_response(conn, context->request(), resp);
                context->reset();
                /*有错误，或者短链接则直接关闭--这里的关闭时会等发送数据完毕后关闭套接字描述符*/
                if (resp.statu >= 400 || resp.is_close()) {
                    conn->shutdown();
                }
            }
        }
        void set_thread_count(int count) {
            return _server.set_thread_count(count);
        }
        void set_base_dir(const std::string &mount_point) {
            if (access(mount_point.c_str(), F_OK) < 0) {
                mkdir(mount_point.c_str(), 0775);
            }
            _base_dir = mount_point;
            return ;
        }
        void Get(const char *pattern, Handler handler){
            _get_handlers.push_back(std::make_pair(std::regex(pattern), handler));
            return ;
        }
        void Post(const char *pattern, Handler handler) {
            _post_handlers.push_back(std::make_pair(std::regex(pattern), handler));
            return ;
        }
        void Put(const char *pattern, Handler handler) {
            _put_handlers.push_back(std::make_pair(std::regex(pattern), handler));
            return ;
        }
        void Delete(const char *pattern, Handler handler) {
            _delete_handlers.push_back(std::make_pair(std::regex(pattern), handler));
            return ;
        }
        void listen(int port, int timeout);
        void start() {
            return _server.start();
        }
    private:
        bool is_file_request(HttpRequest &req) {
            /*没有设置静态资源根目录。或者非GET&HEAD请求则不是文件请求*/
            if (_base_dir.empty() || (req.method != "GET" && req.method != "HEAD")) {
                return false;
            }
            /*请求的文件路径是一个无效路径，有可能跳出了静态资源根目录*/
            bool ret = Util::is_valid_path(req.path);
            if (ret == false) {
                return false;
            }
            /*如果请求的是根目录则默认追加index.html*/
            if (req.path.back() == '/') {
                req.path += "index.html";
            }
            std::string path = _base_dir + req.path;
            
            /*请求的不是一个普通文件实体资源*/
            ret = Util::is_file(path);
            if (ret == false) {
                return false;
            }
            return true;
        }
        void file_handler(const HttpRequest &req, HttpResponse *rsp) {
            bool is_head_request = req.method == "HEAD";
            std::string path = _base_dir + req.path;
            /*不是HEAD请求，则读取文件内容到rsp的body中*/
            if (!is_head_request){
                bool ret = Util::read_file(path, &rsp->body);
                if (ret == false) {
                    rsp->statu = 500;
                    return ;
                }
            }
            std::string mime_type = Util::find_file_mime_type(path);
            rsp->set_header("Content-Type", mime_type);
        }
        void error_handler(const HttpRequest &req, HttpResponse *rsp) {
            rsp->body.clear();
            rsp->body += "<html>";
            rsp->body += "<head>";
            rsp->body += "<meta charset='UTF-8'>";
            rsp->body += "<title>请求错误</title>";
            rsp->body += "</head>";
            rsp->body += "<body>";
            rsp->body += "<h1>";
            rsp->body += std::to_string(rsp->statu);
            rsp->body += " ";
            rsp->body += Util::status_message(rsp->statu);
            rsp->body += "</h1>";
            rsp->body += "</body>";
            rsp->body += "</html>";
            rsp->set_header("Content-Type", "text/html");
        }
        void write_response(const bit_net::ConnectionPtr &conn, HttpRequest &req, HttpResponse &rsp) {
            if (rsp.statu >= 400) error_handler(req, &rsp);
            if (!rsp.has_header("Connection")) {
                if (req.is_close()) {
                    rsp.set_header("Connection", "close");
                } else {
                    rsp.set_header("Connection", "keep-alive");
                }
            }
            if (!rsp.has_header("Content-Type") && !rsp.body.empty()) {
                rsp.set_header("Content-Type", "text/plain");
            }
            if (!rsp.body.empty()) {
                rsp.set_header("Content-Length", std::to_string(rsp.body.size()));
            }
            if (rsp.is_redirect) {
                rsp.set_header("Location", rsp.redirect_url);
            }
            std::stringstream ss;
            ss << req.version << " " << rsp.statu << " " << Util::status_message(rsp.statu) << "\r\n";
            for (auto &it : rsp.headers) {
                ss << it.first << ": " << it.second << "\r\n";
            }
            ss << "\r\n";
            ss << rsp.body;
            conn->send(ss.str().c_str(), ss.str().size());
        }
        void dispatch_request(HttpRequest &req, HttpResponse *rsp, Handlers &handlers) {
            /*尝试使用路由表中的正则匹配规则进行匹配，判断当前请求的资源路径是否符合,符合就使用对应的处理函数进行处理*/
            for (auto &it : handlers) {
                const std::regex &pattern = it.first;
                const auto &handler = it.second;
                bool ret = std::regex_match(req.path, req.matches, pattern);
                if (ret == true) {
                    return handler(req, rsp);
                }
            }
            /*完全在注册的请求路由表中找不到，那就404毁灭吧*/
            rsp->statu = 404;
        }
        void routing(HttpRequest &req, HttpResponse *rsp) {
            if (is_file_request(req)) {
                return file_handler(req, rsp);
            }
            DBG_LOG("not a get file request!,search handle map info!");
            if (req.method == "GET" || req.method == "HEAD") {
                return dispatch_request(req, rsp, _get_handlers);
            }else if (req.method == "POST") {
                return dispatch_request(req, rsp, _post_handlers);
            }else if (req.method == "PUT") {
                return dispatch_request(req, rsp, _put_handlers);
            }else if (req.method == "DELETE") {
                return dispatch_request(req, rsp, _delete_handlers);
            }
            /*非静态资源请求，非当前支持的请求方法，那就405告诉客户端不支持对应的请求方法*/
            rsp->statu = 405;
        }
    private:
        /*存储get请求的映射处理函数*/
        Handlers _get_handlers;
        /*存储post请求的映射处理函数*/
        Handlers _post_handlers;    
        /*存储put请求的映射处理函数*/
        Handlers _put_handlers;     
        /*存储delete请求的映射处理函数*/
        Handlers _delete_handlers;  
        std::string _base_dir;
        bit_net::TcpServer _server;
};


#endif